package com.etop.jansing.service;

import com.etop.jansing.dao.ResourcePermissionDao;
import com.etop.jansing.dao.RoleDao;
import com.etop.jansing.entities.ResourcePermission;
import com.etop.jansing.entities.Role;
import com.etop.jansing.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jansing on 2015/10/25.
 */
@Service
public class RoleService extends BaseService {
    @Resource
    private RoleDao roleDao;
    @Resource
    private ResourcePermissionDao resourcePermissionDao;


    public Role getById(long id) {
        log.info("-->获取id=[" + id + "]的角色");
        Role role = roleDao.get(id);
        if (role == null) {
            log.warn("-->id=[" + id + "]的角色不存在");
        }
        return role;
    }

    public Role getByName(String name) {
        log.info("-->获取name=[" + name + "]的有效角色");
        Role role = roleDao.getByName(name);
        if (role == null) {
            log.warn("-->name=[" + name + "]的有效角色不存在");
        }
        return role;
    }

    public Role getByNameIgnoreValid(String name) {
        log.info("-->获取name=[" + name + "]的角色");
        Role role = roleDao.getByNameIgnoreValid(name);
        if (role == null) {
            log.warn("-->name=[" + name + "]的角色不存在");
        }
        return role;
    }

    public List<Role> getAllRoles() {
        log.info("-->获取角色列表");
        return roleDao.list();
    }

    /**
     * 是否正在被使用（即有某个用户拥有这个角色）
     *
     * @param id
     * @return
     */
    public boolean isUsing(long id) {
        if (roleDao.isUsing(id) > 0) {
            log.info("-->id=[" + id + "]的角色正被使用");
            return true;
        }
        log.info("-->id=[" + id + "]的角色没有被使用");
        return false;
    }

    public void delete(long id) {
        log.info("-->删除id=[" + id + "]的角色");

        Role role = roleDao.get(id);
        if (role == null) {
            log.warn("-->id=[" + id + "]的角色不存在");
            return;
        }
        role.getResourcePermissionList().clear();
        roleDao.delete(role);
    }

    public void saveOrUpdate(Role role, String[] tempRPids) {
        role.getResourcePermissionList().clear();
        if (tempRPids != null && tempRPids.length > 0) {
            List<Long> rpids = CommonUtils.parseIds(tempRPids);
            List<ResourcePermission> newRPList = resourcePermissionDao.getResoPermListByIds(rpids);
            role.getResourcePermissionList().addAll(newRPList);
        }
        if (role.getId() != null && role.getId() > 0) {
            log.info("-->更新角色");
            roleDao.update(role);
        } else {
            log.info("-->保存角色");
            roleDao.save(role);
        }
    }

}
